<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="岗位编码" prop="postCodeLike">
        <el-input
          v-model="queryParams.postCodeLike"
          placeholder="请输入岗位编码"
          clearable
          size="default"
          @keyup.enter="handleQuery"
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item label="岗位名称" prop="postNameLike">
        <el-input
          v-model="queryParams.postNameLike"
          placeholder="请输入岗位名称"
          clearable
          size="default"
          @keyup.enter="handleQuery"
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="岗位状态" clearable size="default" style="width: 240px">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <search-button @click="handleQuery" :perm="['system:post:search']" />
        <reset-button @click="resetQuery" :perm="['system:post:search']" />
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <add-button @click="handleAdd" :perm="['system:post:insert']" />
      <delete-button @click="handleDelete" :disabled="multiple" :perm="['system:post:delete']" />
      <export-button @click="handleExport" :perm="['system:post:export']" />
      <right-toolbar
        v-model:showSearch="showSearch"
        @query-table="getList"
        :perm="['system:post:search']"
      />
    </el-row>

    <el-table v-loading="loading" :data="postList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="岗位编号" align="center" prop="postId" />
      <el-table-column label="岗位编码" align="center" prop="postCode" />
      <el-table-column label="岗位名称" align="center" prop="postName" />
      <el-table-column label="岗位排序" align="center" prop="postSort" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <span :class="scope.row.status === 'N' ? 'text-danger' : ''">{{
            getDictLabel(statusOptions, scope.row.status)
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="160" />
      <el-table-column label="修改时间" align="center" prop="updateTime" width="160" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="160"
      >
        <template #default="scope">
          <text-edit-button @click="handleUpdate(scope.row)" :perm="['system:post:update']" />
          <text-delete-button
            v-if="scope.row.parentId != 0"
            @click="handleDelete(scope.row)"
            :perm="['system:post:delete']"
            :title="'是否确认删除' + scope.row.postName + '?'"
          />
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改岗位对话框 -->
    <drag-dialog
      :title="title"
      :close-on-click-modal="false"
      v-model="open"
      width="500px"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="岗位名称" prop="postName">
          <el-input v-model="form.postName" placeholder="请输入岗位名称" />
        </el-form-item>
        <el-form-item label="岗位编码" prop="postCode">
          <el-input v-model="form.postCode" placeholder="请输入编码名称" />
        </el-form-item>
        <el-form-item label="岗位顺序" prop="postSort">
          <el-input-number v-model="form.postSort" controls-position="right" :min="1" />
        </el-form-item>
        <el-form-item label="岗位状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in statusOptions" :key="dict.dictValue" :value="dict.dictValue">{{
              dict.dictLabel
            }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <dialog-footer @ok="submitForm" @cancel="cancel" />
      </template>
    </drag-dialog>
  </div>
</template>

<script>
import {
  listPost,
  getPost,
  delPost,
  addPost,
  updatePost,
  checkpostNameUnique,
  checkpostCodeUnique
} from '@base/api/base/post'
import { debounceWrapper } from '@/utils/zmids'

export default {
  name: 'BasePost',
  data() {
    const checkpostNameUniqueRule = (rule, value, callback) => {
      checkpostNameUnique(value, this.form.postId).then((response) => {
        if (response.data === false) {
          callback('岗位名称已存在')
        } else {
          callback()
        }
      })
    }
    const checkpostCodeUniqueRule = (rule, value, callback) => {
      checkpostCodeUnique(value, this.form.postId).then((response) => {
        if (response.data === false) {
          callback('岗位编码已存在')
        } else {
          callback()
        }
      })
    }
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 岗位表格数据
      postList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 状态数据字典
      statusOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderBy: 'POST_SORT',
        sortDirect: 'ASC',
        postCodeLike: undefined,
        postNameLike: undefined,
        status: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        postName: [
          { required: true, message: '岗位名称不能为空', trigger: 'blur' },
          { required: true, validator: checkpostNameUniqueRule, trigger: 'blur' }
        ],
        postCode: [
          { required: true, message: '岗位编码不能为空', trigger: 'blur' },
          { required: true, validator: checkpostCodeUniqueRule, trigger: 'blur' }
        ],
        postSort: [{ required: true, message: '岗位顺序不能为空', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getList()
    this.getDicts('sys_normal_disable').then((response) => {
      this.statusOptions = response.data
    })
  },
  methods: {
    /** 查询岗位列表 */
    getList: debounceWrapper(function () {
      this.loading = true
      listPost(this.queryParams).then((response) => {
        this.postList = response.data.list
        this.total = response.data.total
        this.loading = false
      })
    }),
    // 岗位状态字典翻译
    statusFormat(row, column) {
      return selectDictLabel(this.statusOptions, row.status)
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        postId: undefined,
        postCode: undefined,
        postName: undefined,
        postSort: 1,
        status: 'Y',
        remark: undefined
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.postId)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加岗位'
    },
    /** 修改按钮操作 */
    handleUpdate: debounceWrapper(function (row) {
      this.reset()
      const postId = row.postId || this.ids[0]
      getPost(postId).then((response) => {
        this.form = response.data
        this.open = true
        this.title = '修改岗位'
      })
    }),
    /** 提交按钮 */
    submitForm: debounceWrapper(function () {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.form.postId != undefined) {
            updatePost(this.form).then((response) => {
              if (response.data === 1) {
                this.msgSuccess('修改成功')
                this.open = false
                this.getList()
              }
            })
          } else {
            addPost(this.form).then((response) => {
              if (response.data === 1) {
                this.msgSuccess('新增成功')
                this.open = false
                this.getList()
              }
            })
          }
        }
      })
    }),
    /** 删除按钮操作 */
    handleDelete: debounceWrapper(function (row) {
      const postIds = (row && row.postId) || this.ids.join(',')
      delPost(postIds)
        .then(() => {
          this.getList()
          this.msgSuccess('删除成功')
        })
        .catch(function () {})
    }),
    /** 导出按钮操作 */
    handleExport() {
      this.downloadUrl('/system/post/export', { json: JSON.stringify(this.queryParams) })
    },
    getDictLabel(options, value) {
      return this.selectDictLabel(options, value)
    }
  }
}
</script>
